package com.cnct.generic.dubbo.holder;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.RegistryConfig;
import com.cnct.generic.dubbo.properties.GenericDubboProperties;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 注册中心的管理
 *
 * @author wangzhen
 */
@Component
public class RegistryHolder implements InitializingBean {

    private static final Cache<Object, RegistryConfig> registryConfigCache = CacheBuilder.newBuilder()
            .maximumSize(100000)
            .build();

    private GenericDubboProperties properties;

    public RegistryHolder(GenericDubboProperties properties) {
        this.properties = properties;
    }


    /**
     * 获取注册中心信息
     *
     * @param address zk注册地址
     * @return
     */
    public RegistryConfig requireRegistryConfig(String address) {

        //从缓存中获取注册中心配置
        RegistryConfig registryConfig = registryConfigCache.getIfPresent(address);

        if (null == registryConfig) {

            registryConfig = new RegistryConfig();

            if (StringUtils.isNotEmpty(address)) {
                registryConfig.setAddress(address);
            }
            registryConfigCache.put(address, registryConfig);
        }
        return registryConfig;
    }

    /**
     * 从缓存中移除注册中心配置
     *
     * @param address zk注册地址
     */
    public void removeRegistryConfig(String address) {

        registryConfigCache.invalidate(address);

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(() -> this.requireRegistryConfig(properties.getRegistryAddress())).start();
    }
}
